<template>
  <FormDialog
    v-model="visible"
    :title="isEdit ? '编辑栏目' : '添加栏目'"
    :form-data="formData"
    :form-rules="formRules"
    :is-edit="isEdit"
    :loading="loading"
    @submit="handleSubmit"
    @cancel="handleCancel"
  >
    <template #default="{ form, rules }">
      <el-form-item label="上级栏目" prop="parentId">
        <el-tree-select
          v-model="form.parentId"
          :data="treeData"
          :render-after-expand="false"
          :default-expand-all="false"
          :expand-on-click-node="false"
          placeholder="请选择上级栏目（留空为顶级栏目）"
          clearable
          check-strictly
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="栏目名称" prop="name" required>
        <el-input
          v-model="form.name"
          placeholder="请输入栏目名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="英文名称" prop="englishName">
        <el-input
          v-model="form.englishName"
          placeholder="请输入英文名称"
          maxlength="50"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="栏目描述" prop="description">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入栏目描述"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="栏目级别" prop="level">
            <el-input
              v-model="form.level"
              placeholder="请输入级别"
              maxlength="10"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input-number
              v-model="form.sort"
              :min="0"
              :max="9999"
              :step="1"
              placeholder="数值越小越靠前"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="是否显示">
            <el-switch
              v-model="form.isVisible"
              :active-value="true"
              :inactive-value="false"
              active-text="显示"
              inactive-text="隐藏"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="允许投稿">
            <el-switch
              v-model="form.allowSubmit"
              :active-value="true"
              :inactive-value="false"
              active-text="允许"
              inactive-text="不允许"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="SEO关键词" prop="seoKeywords">
        <el-input
          v-model="form.seoKeywords"
          placeholder="请输入SEO关键词，多个用逗号分隔"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <el-form-item label="SEO描述" prop="seoDescription">
        <el-input
          v-model="form.seoDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入SEO描述"
          maxlength="300"
          show-word-limit
        />
      </el-form-item>
    </template>
  </FormDialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import FormDialog from '@/components/common/FormDialog.vue'
import { categoryApi } from '@/api/category'

// Props
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  category: {
    type: Object,
    default: null
  },
  parentId: {
    type: String,
    default: null
  },
  categoryList: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'success'])

// 响应式数据
const loading = ref(false)

// 表单数据
const formData = reactive({
  id: null,
  parentId: null,
  name: '',
  englishName: '',
  description: '',
  level: '',
  sort: 50,
  isVisible: true,
  allowSubmit: false,
  seoKeywords: '',
  seoDescription: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入栏目名称', trigger: 'blur' },
    { min: 1, max: 50, message: '栏目名称长度在1-50个字符', trigger: 'blur' }
  ],
  englishName: [
    { max: 50, message: '英文名称长度不能超过50个字符', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]*$/, message: '英文名称只能包含字母、数字、下划线和连字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过200个字符', trigger: 'blur' }
  ],
  level: [
    { max: 10, message: '级别长度不能超过10个字符', trigger: 'blur' }
  ],
  sort: [
    { type: 'number', message: '排序必须是数字', trigger: 'blur' }
  ],
  seoKeywords: [
    { max: 200, message: 'SEO关键词长度不能超过200个字符', trigger: 'blur' }
  ],
  seoDescription: [
    { max: 300, message: 'SEO描述长度不能超过300个字符', trigger: 'blur' }
  ]
}

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit('update:modelValue', val)
})

const isEdit = computed(() => !!props.category)

const treeData = computed(() => {
  return buildTreeSelectData(props.categoryList)
})

// 构建TreeSelect数据
const buildTreeSelectData = (list) => {
  const tree = []
  const map = {}
  
  // 创建映射，过滤掉当前编辑的节点及其子节点
  list.forEach(item => {
    if (props.category && (item.id === props.category.id || isDescendant(item.id, props.category.id))) {
      return
    }
    
    map[item.id] = {
      value: item.id,
      label: item.name,
      children: []
    }
  })
  
  // 构建树形结构
  list.forEach(item => {
    if (props.category && (item.id === props.category.id || isDescendant(item.id, props.category.id))) {
      return
    }
    
    if (item.parentId && map[item.parentId]) {
      map[item.parentId].children.push(map[item.id])
    } else if (!item.parentId) {
      tree.push(map[item.id])
    }
  })
  
  return tree
}

// 检查是否是子孙节点
const isDescendant = (nodeId, ancestorId) => {
  const node = props.categoryList.find(item => item.id === nodeId)
  if (!node || !node.parentId) return false
  
  if (node.parentId === ancestorId) return true
  return isDescendant(node.parentId, ancestorId)
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: null,
    parentId: null,
    name: '',
    englishName: '',
    description: '',
    level: '',
    sort: 50,
    isVisible: true,
    allowSubmit: false,
    seoKeywords: '',
    seoDescription: ''
  })
}

// 监听器
watch(() => props.modelValue, (newVal) => {
  if (newVal) {
    resetForm()
    if (props.category) {
      Object.assign(formData, props.category)
    }
    if (props.parentId) {
      formData.parentId = props.parentId
    }
  }
})

// 提交表单
const handleSubmit = async (data) => {
  try {
    loading.value = true
    
    let response
    if (isEdit.value) {
      response = await categoryApi.update(data.id, data)
    } else {
      response = await categoryApi.create(data)
    }
    
    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      emit('success')
      visible.value = false
    }
  } catch (error) {
    ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    console.error('Submit error:', error)
  } finally {
    loading.value = false
  }
}

// 取消
const handleCancel = () => {
  visible.value = false
}
</script>